const db = require("../models");
const DAO = require("../dao/DAO");
const Depts = db.models.depts;

/** 新增|修改 */
function addOrUpdate(data, cb) {
    if (!data.name) return cb({ data: null, code: -1, message: "部门名称为空！" });
    let role = {
        parent_id: data.parent_id || 0,
        name: data.name,
        leader: data.leader,
        phone: data.phone,
        email: data.email,
        sort: data.sort,
        status: data.status ?? true,
        remark: data.remark,
    }
    if (!data.id) { // 新增
        // Depts.findOne({ where: { name: data.name } }).then(_ => {
        //     if (_ && _.id) return cb({ data: null, code: -1, message: "部门名称已存在！" });
        DAO.create(Depts, role, res => {
            cb(res)
        })
        // })
    } else { // 修改
        DAO.update(Depts, role, { id: data.id }, res => {
            cb(res)
        })
    }
}


/** 新增 */
exports.create = async (req, res) => {
    const pm = req.body;
    addOrUpdate(pm, (data) => {
        res.sendResult(data)
    })
};
/** 更新 */
exports.update = (req, res) => {
    const pm = req.body;
    // 请求验证
    if (!pm.id) return res.sendResult({ data: '', code: -1, message: "ID不能为空！" })
    addOrUpdate(pm, (data) => {
        res.sendResult(data)
    })
};
/** 所有list */
exports.findAll = async (req, res) => {
    let pm = {
        current_page: 0,
        params: {
            name: req.body?.name ? { [db.Op.substring]: req.body?.name ?? '' } : '',
            code: req.body?.code ? { [db.Op.substring]: req.body?.code ?? '' } : '',
            status: req.body?.status??'',
        }
    }
    DAO.listAll(Depts, pm, list => {
        res.sendResult(list)
    })
};
/** 单个 */
exports.findOne = (req, res) => {
    const pm = req.body;
    DAO.findOne(Depts, pm, data => {
        res.sendResult(data)
    })
};


/** 删除 */
exports.delete = (req, res) => {
    const pm = req.body;
    // 请求验证
    if (!pm.id) return res.sendResult({ data: '', code: -1, message: "ID不能为空！" })
    DAO.delete(Depts, { id: pm.id }, data => {
        res.sendResult(data)
    })
};
